import $ from "jquery"
import "babel-polyfill"
import {Simulation} from "./fake/simulation"
import MRG32k3a from "./common/utils/MRG32k3a";
import Grid from "./fake/grid";
import axios from 'axios'

$(function(){
    //  定义四旋翼无人机图片对象
    const uavImg = new Image();
    uavImg.src = './imgs/UAV.svg';
    uavImg.onload = ()=>{
        // 获得canvas对象
        const canvas = document.getElementById("main");
        // 创建simulation对象
        const simulation = new Simulation(canvas, uavImg);
        simulation.canvas.width = window.innerHeight;
        simulation.canvas.height = window.innerHeight - 70;
        // 生成新的随机seed
        simulation.prng = new MRG32k3a();
        // 绑定按钮
        bindButton(simulation);
        // 给全局增加改变大小的事件，使得canvas大小自适应
        window.addEventListener("resize", simulation.adjustAndRedraw.bind(simulation), false);
        // 给canvas内增加点击事件
        simulation.canvas.addEventListener("click", simulation.handleClick.bind(simulation), false);
        // 初始化网格
        simulation.flock.addGrid(new Grid(canvas, simulation.gridSize, simulation.targetNum));  // 绘制网格
        // 从储存中增加目标
        simulation.flock.add_targets_from_store();
        autoClick(simulation, 5000)
        // 绘制canvas
        simulation.redraw();
        // 每秒30帧
        let fps = 30;
        // 每隔一定时间执行update方法
        setInterval(()=>{
            simulation.update()
        }, 1000 / fps);
    };
});

/**
 * 页面上的按钮与方法进行绑定
 * @param simulation
 */
function bindButton(simulation){
    // 给body增加一个改变事件,其他元素会冒泡到这里
    $("body").on('change', simulation.setParams.bind(simulation));
    // "重新生成"按钮的绑定
    $("#init_btn").on('click', simulation.rebuildTargets.bind(simulation));
    // "开始计算"按钮的绑定
    $("#start_btn").on('click', simulation.pauseOrRun.bind(simulation));

    $('#copyVelBtn').on('click',simulation.copyVelHistory.bind(simulation));
    $('#copyPosBtn').on('click',simulation.copyPosHistory.bind(simulation));
}

/**
 * 等待10秒钟,如果10秒内没有点击,则自动点击
 * @param timeout
 */
function autoClick(simulation, timeout){
    setTimeout(function(){
        const uavNum = simulation.flock.uav_list.length || 0;
        if(uavNum === 0){
            const init_x = $("#init_X").val() || localStorage.getItem("init_X") || 200;
            const init_y = $("#init_Y").val() || localStorage.getItem("init_Y") || 200;
            simulation.handleClick({clientX: init_x, clientY: init_y})
        }
    }, timeout);
}




